package com.byyy.ccts.modules.sys.service.impl;

import com.byyy.ccts.modules.sys.entity.User;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service("passwordService")
public class PasswordService {

	private RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();
	
	@Value(value = "${shiro.credentials.hashAlgorithmName}")
	private String algorithmName = "md5";
	@Value(value = "${shiro.credentials.hashIterations}")
	private final int hashIterations = 2;

	public void encryptPassword(User user) {
		user.setSalt(randomNumberGenerator.nextBytes().toHex());
		String newPassword = new SimpleHash(algorithmName, user.getPassword(),
				ByteSource.Util.bytes(user.getCredentialsSalt()), hashIterations).toHex();
		user.setPassword(newPassword);
	}

	/**
	 * 比较用户与数据库内用户密码是否相同
	 * @param user
	 * @return
	 */
	public boolean compareUserPassword(User user, String password) {
		SimpleHash hash = new SimpleHash(algorithmName, password,
				ByteSource.Util.bytes(user.getCredentialsSalt()), hashIterations);
		if (user.getPassword().equals(hash.toHex())) {
			return true;
		}

		return false;
	}
}
